package com.group.transaction.service.logistics.impl;

import com.alibaba.fastjson.JSONObject;
import com.group.transaction.common.IntegralData;
import com.group.transaction.domain.*;
import com.group.transaction.hander.ServiceDataHandler;
import com.group.transaction.enums.IntegralLogTypeEmun;
import com.group.transaction.exception.SystemException;
import com.group.transaction.mapper.*;
import com.group.transaction.model.ResultJson;
import com.group.transaction.service.logistics.LogisticsService;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
public class LogisticsServiceImpl implements LogisticsService {

    @Resource
    private LogisticsMapper logisticsMapper;

    @Resource
    private IntegralMapper integralMapper;

    @Resource
    private IntegralLogMapper integralLogMapper;

    @Resource
    private ServiceDataHandler serviceDataHandler;

    @Resource
    private UserMapper userMapper;

    @Resource
    private OperationLogMapper operationLogMapper;

    /**
     * 添加物流
     *
     * @param logistics
     * @return
     */
    @Override
    @Transactional
    public ResultJson addLogistics(Logistics logistics) {
        User user = null;
        if(logistics.getUserId() != null) {
             user = userMapper.queryUserDataByUserId(logistics.getUserId());
        }else {
             user = (User) SecurityUtils.getSubject().getSession().getAttribute("user");
        }

        Long userId = user.getId();
        logistics.setUserId(userId);
        logistics.setStatus(1);
        logistics.setTime(new Date());
        if(logistics.getIntegralUse() != null) {
            Integral userIntegral = integralMapper.findFirstByUserId(logistics.getUserId());
            int total = logisticsMapper.findCountByUserId(user.getId());
            if(userIntegral != null && total != 10  ) {
                userIntegral.setIntegralUse(userIntegral.getIntegralUse() - logistics.getIntegralUse());
                userIntegral.setIntegralUnsed(userIntegral.getIntegralUnsed() + logistics.getIntegralUse());
                integralMapper.updateByPrimaryKey(userIntegral);
            }
        }
        int num = logisticsMapper.insert(logistics);
        if(num > 0) {
            IntegralLog integralUseLog = new IntegralLog();
            integralUseLog.setUserId(user.getId());
            integralUseLog.setContent("待取件中");
            integralUseLog.setIntegral("--");
            integralUseLog.setType(3);
            integralUseLog.setTime(new Date());
            integralUseLog.setLogisticsId(logistics.getId());
            integralLogMapper.insert(integralUseLog);
            OperationLog operationLog = new OperationLog();
            operationLog.setContent((user.getShowName() != null ? user.getShowName() : "--")  +"——新增了一个物流");
            operationLog.setType(4);
            operationLog.setTime(new Date());
            operationLogMapper.insert(operationLog);
            return ResultJson.builder().code(1).message("添加物流成功").build();
        }else {
            return ResultJson.builder().code(-1).message("添加物流失败").build();
        }
    }

    /**
     * 查询全部物流
     *
     * @param logistics
     * @return
     */
    @Override
    public JSONObject queryLogisticsAllData(Logistics logistics) {
        try {

            List<Logistics> logisticsList = logisticsMapper.queryLogisticsData(logistics);
            Integer total = logisticsMapper.queryLogisticsDataTotal(logistics);
            return new JSONObject().fluentPut("result", logisticsList).fluentPut("total", total);
        } catch (Exception e) {
            return new JSONObject().fluentPut("result", null);
        }
    }
    /**
     * 保存寄件信息
     * @param logistics
     * @return
     */
    @Override
    @Transactional
    public ResultJson saveLogisticsData(Logistics logistics){
        //获取当前用户积分
        Integral userIntegral = integralMapper.findFirstByUserId(logistics.getUserId());
        double price = 0.0;
        if(logistics.getIdentityCardSign() != null) {
            User user = new User();
            user.setId(logistics.getUserId());
            user.setIdentityCard(logistics.getIdentityCard());
            int sign = userMapper.updateIdentityCardByUserId(user);
        }
        Integer total = logisticsMapper.findCountByUserId(logistics.getUserId());
        if(total == 10) {
            int num = logisticsMapper.updateLogisticsData(logistics);
            if(num > 0) {
                return ResultJson.builder().code(1).message("保存物流成功").result(-1).build();
            } else {
                return ResultJson.builder().code(-1).message("保存物流失败").build();
            }
        }
        if(logistics.getStatus() == 4) {
            /*
              完成订单，计算使用积分、实际花费多少钱
             */
            price = logistics.getPrice();
            if(logistics.getIntegralUse() != null && logistics.getIntegralUse() > 0) {
                /*
                 抵扣积分计算
                 */
                int integralUse = logistics.getIntegralUse() / 30;
                price = price - integralUse;
                IntegralLog integralUseLog = new IntegralLog();
                integralUseLog.setUserId(logistics.getUserId());
                integralUseLog.setContent("积分兑换");
                integralUseLog.setIntegral("-"+ logistics.getIntegralUse());
                integralUseLog.setTime(new Date());

                integralLogMapper.insert(integralUseLog);
                User loginUser = (User) SecurityUtils.getSubject().getSession().getAttribute("user");
                OperationLog operationLog = new OperationLog();
                operationLog.setContent(loginUser.getShowName() != null ? loginUser.getShowName() : "--"  +"提取了【"+ logistics.getShowName() +"】的物流");
                operationLog.setType(5);
                operationLog.setTime(new Date());
                operationLogMapper.insert(operationLog);
            }
            Double integral = IntegralData.getIntegral(price,total);
            IntegralLog integralLog = integralLogMapper.queryIntegralLogByLogisticsId(logistics.getId());
            integralLog.setContent("【寄】"+ logistics.getAddress());
            integralLog.setIntegral("+"+ integral);
            integralLog.setTime(new Date());
            if(userIntegral == null) {
                userIntegral = new Integral();
                userIntegral.setMoney(price);
                userIntegral.setIntegralUse(userIntegral.getIntegralUse() + integral);
                userIntegral.setIntegralTotal(userIntegral.getIntegralTotal() + integral);
                userIntegral.setUserId(logistics.getUserId());
                integralMapper.insert(userIntegral);
            }else {
                userIntegral.setMoney(userIntegral.getMoney() + price);
                userIntegral.setIntegralUse(userIntegral.getIntegralUse() + integral);
                userIntegral.setIntegralTotal(userIntegral.getIntegralTotal() + integral);
                integralMapper.updateByPrimaryKey(userIntegral);
            }
            integralLogMapper.updateByPrimaryKey(integralLog);
            logistics.setMoney(price);
        }
        int num = logisticsMapper.updateLogisticsData(logistics);
        if(num > 0) {
            return ResultJson.builder().code(1).message("保存物流成功").result(price).build();
        } else {
            return ResultJson.builder().code(-1).message("保存物流失败").build();
        }
    }
    /**
     * 查询客户寄的单数
     * @param
     * @return
     */
    @Override
    public ResultJson queryLogisticsCountTotal() {
        User user = (User) SecurityUtils.getSubject().getSession().getAttribute("user");
        int total = logisticsMapper.findCountByUserId(user.getId());
        return ResultJson.builder().code(1).message("客户寄总单数").result(total).build();
    }
    /**
     * 根据物流id查询物流信息
     * @param
     * @return
     */
    @Override
    public ResultJson queryLogisticsDataById(Long id) {
        User user = (User) SecurityUtils.getSubject().getSession().getAttribute("user");
        if(user == null) {
            return ResultJson.builder().code(-999).message("登录失效").build();
        }
        Logistics logistics = logisticsMapper.queryLogisticsDataById(id);
        return ResultJson.builder().code(1).message("成功获取数据").result(logistics).build();
    }
}
